# -*- coding: utf-8 -*-
import threading
from zc_core.client.mongo_client import Mongo
from zc_core.model.items import ItemData, Spu, ItemPoolData


class GovCatHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(GovCatHelper, "_instance"):
            with GovCatHelper._instance_lock:
                if not hasattr(GovCatHelper, "_instance"):
                    GovCatHelper._instance = object.__new__(cls)
        return GovCatHelper._instance

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.mongo = Mongo()
            coll = self.mongo.get_collection('gov_cat_pool')
            self.id_name_dict = dict()
            self.name_id_dict = dict()
            if coll:
                pool = coll.find()
                if pool:
                    for cat in pool:
                        self.id_name_dict[cat.get('_id')] = cat.get('catalogName')
                        self.name_id_dict[cat.get('catalogName')] = cat.get('_id')

    def fill(self, item):
        # 过滤条件
        if isinstance(item, ItemData) or isinstance(item, Spu) or isinstance(item, ItemPoolData):
            if item.get('govCatId') and not item.get('govCatName'):
                name = self.id_name_dict.get(item.get('govCatId'))
                if name:
                    item['govCatName'] = name
            elif item.get('govCatName') and not item.get('govCatId'):
                id = self.name_id_dict.get(item.get('govCatName'))
                if id:
                    item['govCatId'] = id

        return item

    def get_by_name(self, name):
        if name:
            return self.name_id_dict.get(name)

    def get_by_id(self, id):
        if id:
            return self.id_name_dict.get(id)

    # 关闭链接
    def close(self):
        self.mongo.close()
